package server;

import java.nio.ByteBuffer;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class StringUtility {
	
	/*
	 * convert bytes to a string of hex
	 */
	public static String toHexString(byte[] b) {
	    StringBuffer sb = new StringBuffer();
	    for (int i = 0; i < b.length; i++){
	    	sb.append(Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1));
	    }
	    return sb.toString();
	}
	
	/*
	 * convert a string of hex to bytes
	 */
	
	public static byte[] toByteArray(String s) {
	    int len = s.length();
	    byte[] data = new byte[len / 2];
	    for (int i = 0; i < len; i += 2) {
	        data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
	                             + Character.digit(s.charAt(i+1), 16));
	    }
	    return data;
	}
	
	/*
	 * Print an array that contains bytes
	 */
	public static void printHex(String description, byte[] bArray, int szArr){
		System.out.print(description + ": ");
		for (int i = 0; i < szArr; i++){
			System.out.printf("%02x ", bArray[i]);
		}
		System.out.println();
	}
	
	public static void printHex(String description, String s){
		byte[] bArr = toByteArray(s);
		printHex(description, bArr, bArr.length);
	}
	/*
	 * Represent a long integer to a byte array
	 */
	public static String toHexString(long number){
		ByteBuffer bb = ByteBuffer.allocate(8);
		bb.putLong(number);
		return StringUtility.toHexString(bb.array());
	}
	
	/*
	 * Return the current time 
	 */
	public static String getCurrentTime(){
		Calendar cal = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String time = sdf.format(cal.getTime());
		return time;
	}
	
	/*
	 * Subtract two times time1 - time2
	 * returned result is in milliseconds
	 */
	public static long subtractTimes(String time1, String time2){
		try{
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date date1 = df.parse(time1);
			Date date2 = df.parse(time2);
			return date1.getTime() - date2.getTime();
		}
		catch(java.text.ParseException pe){
			pe.printStackTrace();
			return 0;
		}
	}
	
}
